﻿using Abp.Runtime.Session;
using Hicap.AuthorizationServer.Core.Common.EFCore;
using Hicap.AuthorizationServer.Core.Models;
using Newtonsoft.Json;
using Serilog;
using System;

namespace Hicap.AuthorizationServer.Core.Managers
{
    public class AuthObjectManager : ManagerBase<AuthObject>, IAuthObjectManager
    {
        public AuthObjectManager(IUnitOfWork unitOfWork, IAbpSession session) : base(unitOfWork)
        {
            QueryCondition.Add(x => x.IsDeleted == false);
            CreateActions.Add(x => x.CreatorUserId = session.UserId);
            CreateActions.Add(x => x.CreationTime = DateTime.Now);
            UpdateActions.Add(x => x.LastModificationTime = DateTime.Now);
            UpdateActions.Add(x => x.LastModifierUserId = session.UserId);
            DeleteActions.Add(x => x.DeletionTime = DateTime.Now);
            DeleteActions.Add(x => x.DeleterUserId = session.UserId);
            DeleteActions.Add(x => x.IsDeleted = true);

            CreateCheckActions.Add(x =>
            {
                if (x.Id == 0) return true;
                Log.Warning($"AuthObject CreateCheck Fail : {JsonConvert.SerializeObject(x)}");
                return false;
            });
            UpdateCheckActions.Add(x =>
            {
                if (x.Id > 0 && x.IsDeleted == false) return true;
                Log.Warning($"AuthObject UpdateCheck Fail : {JsonConvert.SerializeObject(x)}");
                return false;
            });
            DeleteCheckActions.Add(x =>
            {
                if (x.IsDeleted == false) return true;
                Log.Warning($"AuthObject DeleteCheck Fail : {JsonConvert.SerializeObject(x)}");
                return false;
            });
        }

        public AuthObject GetAuthById(int authObjectId)
        {
            return Repository.Get(authObjectId);
        }
    }
}